package com.feiyu.queue;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Worker {

	private static final String QUEUE_NAME = "task";

	public static void execute(String name) throws IOException, TimeoutException {
		ConnectionFactory factory = new ConnectionFactory();
		factory.setHost("localhost");
		// 这里不使用try-with-resource，因为需要保持活动状态持续监听
		Connection connection = factory.newConnection();
		Channel channel = connection.createChannel();
		// 这里也声明队列，保证无论是发布者还是消费者，在连接之前队列已经存在
		// 消费的队列名应与发布的命名相匹配
		channel.queueDeclare(QUEUE_NAME, false, false, false, null);
		System.out.println(" [*] Waiting for messages");
		// 服务器异步推送消息过来，这里以接口的对象形式提供回调，用于处理消息
		DeliverCallback deliverCallback = (consumerTag, delivery) -> {
			byte seconds = delivery.getBody()[0];
			System.out.println(" [x] Worker " + name + " 接受任务，任务难度 " + seconds + " 秒");
			try {
				Thread.sleep(seconds * 1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			} finally {
				System.out.println(" [x] Worker " + name + " 处理任务，处理时间 " + seconds + " 秒");
			}
		};
		channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> {});
	}
}
